package com.qfedu.ssm.utils;

import com.qfedu.ssm.dao.PermissionDAO;
import com.qfedu.ssm.dao.RoleDAO;
import com.qfedu.ssm.dao.UserDAO;
import com.qfedu.ssm.pojos.User;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import java.util.Set;

@Controller
public class MyRealm extends AuthorizingRealm {

    @Autowired
    private UserDAO userDAO;
    @Autowired
    private RoleDAO roleDAO;
    @Autowired
    private PermissionDAO permissionDAO;

    @Override
    public String getName(){
        return "myRealm01";
    }

    /**
     * 授权
     * @param principalCollection
     * @return
     */
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //1.获取授权用户信息(principalCollection存放了认证成功的用户信息)
        User user=(User)principalCollection.iterator().next();
        int userId=user.getId();

        //2.通过user的id查询当前用户的所有的角色名--Set<String>
        Set<String> roles=roleDAO.queryRolesByUserId(userId);

        //3.通过user的id查询当前用户的所有权限
        Set<String> permissions=permissionDAO.queryPermissionsByUserId(userId);

        SimpleAuthorizationInfo authorizationInfo=new SimpleAuthorizationInfo();
        authorizationInfo.setRoles(roles);
        authorizationInfo.setStringPermissions(permissions);
        return authorizationInfo;
    }

    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //1.从token中获取用户名
        UsernamePasswordToken token =(UsernamePasswordToken) authenticationToken;
        String username=token.getUsername();
        String password=new String(token.getPassword());
        String md5Pwd =new SimpleHash("MD5",password).toHex();
        //2.根据用户名查询数据库（UserDAO）,得到一个User对象
        User user =userDAO.queryUserName(username);
        if(user==null){
            throw new UnknownAccountException("账号不存在！");
        }else{
            //用户存在验证密码
            if(!user.getUserPwd().equals(md5Pwd)){
                throw new IncorrectCredentialsException("密码错误");
            }
        }
        return new SimpleAuthenticationInfo(user,password,getName());
    }


}
